#include "stdafx.h"
#include "ConsoleOutWithColor.h"
#include <Windows.h>
#include <stdio.h>
//#include <windows.h>
#include <Fcntl.h>
#include <io.h>


void ConsoleOutWithColor::print(unsigned short color, char* str, ...)
{
	va_list args;
	va_start(args, str);
	cout(color, str, args);
	va_end(args);
}
void ConsoleOutWithColor::print(char* str, ...)
{
	va_list args;
	va_start(args, str);
	cout(ConsoleColor::ForegroundLightGreen, str, args);
	va_end(args);
}
void ConsoleOutWithColor::cout(unsigned short color, char* strFormat, const va_list& args)
{
	WORD colorOld;
	HANDLE handle = ::GetStdHandle(STD_OUTPUT_HANDLE);
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	GetConsoleScreenBufferInfo(handle, &csbi);
	colorOld = csbi.wAttributes;
	SetConsoleTextAttribute(handle, color);

	char szBuffer[1024] = { 0 };
	vsprintf_s(szBuffer, strFormat, args);
	printf(szBuffer);

	SetConsoleTextAttribute(handle, colorOld);
}

void ConsoleOutWithColor::InitConsoleWindow()
{
	int nCrt = 0;
	FILE* fp;
	AllocConsole();
	nCrt = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
	fp = _fdopen(nCrt, "w");
	*stdout = *fp;
	setvbuf(stdout, NULL, _IONBF, 0);
}
void ConsoleOutWithColor::DeinitConsoleWindow()
{
	FreeConsole();
}